package network.protocol;
import physics.PhysicalConstants;
import main.Config;
import network.NetworkConstants;
import network.byteConversions.ByteConverter;
import network.dataFormats.NetworkPackage;
public class FPSHandler {
	private int fps = Config.MAXFPS;
	public void handle(NetworkPackage p, float time, int currentFps) {
		byte[] data = p.getData();
		float serverGameTime = ByteConverter.bytesToFloat(data, 0);
		float clientGameTime = time;
		long serverCurrentTime = ByteConverter.bytesToLong(data, 4);
		long clientCurrentTime = System.currentTimeMillis();
		int serverFps = ByteConverter.bytesToInt(data, 12);
		// The package contains the time from the server at the moment the
		// package was sent.
		// Estimate the current time by taking the time difference it took the
		// package to get sent, multiply with the frames per second and the time
		// step of each frame.
		float localTimeDiff = (clientCurrentTime - serverCurrentTime) * 0.001f;
		serverGameTime = serverGameTime + localTimeDiff * serverFps * PhysicalConstants.DT;
		if (clientGameTime > serverGameTime + NetworkConstants.ALLOWEDTIMEDIFF) { // The
																					// client
																					// is
																					// faster
																					// than
																					// the
																					// server.
																					// Set
																					// the
																					// fps
																					// to
																					// serverFps
																					// -
																					// some
																					// fps
																					// so
																					// the
																					// server
																					// will
																					// catch
																					// up
			fps = serverFps - NetworkConstants.REGULATEFPS;
		}
		else if (clientGameTime < serverGameTime - NetworkConstants.ALLOWEDTIMEDIFF) { // The client is too slow,
																						// try to increase the
																						// fps to catch up with
																						// the server
			fps = serverFps + NetworkConstants.REGULATEFPS;
		}
		else {
			fps = serverFps;
		}
		if (fps < Config.MINFPS) { // Everything below a certain fps number
									// looks bad anyway, at least run with some
									// fps so the game doesn't crash. Hope this
									// never really happens
			fps = Config.MINFPS;
		}
		// if (fps > Config.MAXFPS){ // Never run with more than the maxFps? I
		// don't know ... maybe?
		// fps = Config.MAXFPS;
		// }
	}
	public int getWantedFps() {
		return fps;
	}
}
